package com.stedu.mall.userservice.controller;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.PageInfo;
import com.stedu.mall.common.bean.RespBean;
import com.stedu.mall.common.bean.User;
import com.stedu.mall.common.bean.UserLogin;
import com.stedu.mall.common.exception.MallException;
import com.stedu.mall.common.service.UserLoginService;
import com.stedu.mall.common.service.UserService;
import com.stedu.mall.common.utils.JwtUtils;
import com.stedu.mall.common.utils.RedisUtil;
import com.stedu.mall.common.annotation.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserService userService;
    @Autowired
    private UserLoginService userLoginService;
    @GetMapping("/captcha")
    public RespBean captcha(){
        //创建验证码对象
        LineCaptcha captcha = new LineCaptcha(120, 32, 4, 10);
        //生成唯一的key - 雪花算法
        String key = IdUtil.getSnowflakeNextIdStr();
        redisUtil.set(key, captcha.getCode(),60);
        //将验证码图片转换成Base64编码形式
        String imageBase64Data = captcha.getImageBase64Data();
        //将key和Base64保存在map中
        HashMap<String, Object> map = new HashMap<>();
        map.put("key", key);
        map.put("imageBase64Data",imageBase64Data);
        //将key和Base图片返回
        return RespBean.ok("生成验证码成功",map);
    }

    @PostMapping("/login")
    public RespBean login(String username,
                          String password,
                          String key,
                          String captchaInput) throws MallException {
        //判断验证码是否正确 - 从redis中查询验证码是否存在
        String captcha = (String)redisUtil.get(key);
        if (captcha == null || !captcha.equalsIgnoreCase(captchaInput)) {
            throw new MallException("验证码错误，请重新生成验证码");
        }
        //登录
        User user = userService.login(username, password);
        //生成token
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", user.getId());
        map.put("username", user.getUsername());
        map.put("role", "user");
        //将token返回给用户
        String jwt = JwtUtils.generateJwt(map);
        return RespBean.ok("登录成功",jwt);
    }
    //获取已登录的信息
    @GetMapping("/info")
    public RespBean getInfo(@RequestHeader("token") String token){
        //解析token
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        //获取用户id - 根据id查询用户信息
        Integer id = (Integer)map.get("id");
        User user = userService.selectById(id);
        //返回
        return RespBean.ok("",user);
    }

    //添加 - 注册
    @PostMapping("/reg")
    public RespBean insert(String username,
                           String password,
                           String key,
                           String captchaInput) throws MallException {
        //判断验证码是否正确 - 从redis中查询验证码是否存在
        String captcha = (String)redisUtil.get(key);
        if (captcha == null || !captcha.equalsIgnoreCase(captchaInput)) {
            throw new MallException("验证码错误，请重新生成验证码");
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        userService.reg(user);
        return RespBean.ok("注册成功");
    }
    //根据id删除
    @DeleteMapping(("/{id}"))
    public RespBean delete(@PathVariable("id") Integer id) throws MallException {
        if (!userService.delete(id)) {
            return RespBean.ok("禁用失败");
        }

        return RespBean.ok("禁用成功");
    }
    //根据id修改
    @PutMapping
    public RespBean update(@RequestBody User user) throws MallException {
        if (!userService.update(user)) {
            return RespBean.ok("修改失败");
        }
        return RespBean.ok("修改成功");
    }

    //充值
    @Log(name = "账户充值")
    @PutMapping("/recharge")
    public RespBean recharge(@RequestBody User user, @RequestHeader("token") String token) throws MallException {
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        Integer userId= (Integer)map.get("id");
        userService.recharge(user,userId);
        return RespBean.ok("充值成功");
    }
    //修改密码
    @PutMapping("/chgPwd")
    public RespBean chgPwd(@RequestBody Map<String, Object> map) throws MallException {
        String newPwd = (String) map.get("newPassword");
        String OldPwd = (String) map.get("oldPassword");
        String confirmPwd = (String) map.get("confirmPassword");
        Integer id = (Integer) map.get("id");


        if (!userService.chgPwd(newPwd, OldPwd, confirmPwd, id)) {
            return RespBean.ok("修改失败");
        }
        return RespBean.ok("修改成功");
    }
    //修改支付密码
    @PutMapping("/chgPayPwd")
    public RespBean chgPayPwd(@RequestBody Map<String, Object> map) throws MallException {
        String oldPassword = (String) map.get("oldPassword");
        String oldPayPwd = (String) map.get("oldPayPwd");
        String newPayPwd = (String) map.get("newPayPwd");
        String confirmPayPwd = (String) map.get("confirmPayPwd");
        Integer id = (Integer) map.get("id");


        if (!userService.chgPayPwd(oldPassword, oldPayPwd, newPayPwd,confirmPayPwd, id)) {
            return RespBean.ok("修改失败");
        }
        return RespBean.ok("修改成功");
    }
    //条件分页搜索
    @GetMapping
    public RespBean selectByPage (User condition, Integer pageNum, Integer pageSize){
        pageNum = pageNum == null ? 1 : pageNum;
        pageSize = pageSize == null ? 10 : pageSize;

        PageInfo<User> pageInfo = userService.selectByCondition(condition, pageNum, pageSize);

        return RespBean.ok("",pageInfo);
    }

    //日志信息查询
    @GetMapping("/log")
    public RespBean selectByUserLog (@RequestHeader("token") String token){
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        String username= (String)map.get("username");
        List<UserLogin> list = userLoginService.selectByUserName(username);

        return RespBean.ok("",list);
    }
    //根据id查询
    @GetMapping("/{id}")
    public RespBean selectById(@PathVariable("id") Integer id){
        return RespBean.ok("",userService.selectById(id));
    }
    //订单最多的前五用户
    @GetMapping("/userTop5")
    public RespBean userTop (){


        List<Map<String, Object>> userTop5 = userService.userTop5();

        return RespBean.ok("",userTop5);
    }
}
